<?php
	require_once('paths.inc');
    require_once('security.inc');

    require_once('page.inc');    
    require_once('utils.inc');
    require_once(DB_PATH.'db.inc');    
    include (INCLUDE_PATH.'constants.inc');
    
	session_start();
    check_permissions(CT_PERM_COMENZI);
	
	function curata($var) {
		return !($var == "");
	}
	
	$db = db_connect();
	$indecsi = $_GET['indecsi'];
	$index_arr = explode(";", $indecsi);
	
	select_language();
		
	$index_arr = array_filter($index_arr, "curata");
	$id_client = $_SESSION['user_logat']->id_client;
	$comenzi = array();
	$firme_exec = array();
	
	for ($i = 0; $i < count($index_arr); $i++) {
		try {
			$comenzi[$i] = Comanda::queryLoadByIdWithAllData($db, $index_arr[$i], $id_client);
            $firme_exec[$i] = Firma::queryLoadById($db, $comenzi[$i]->id_firma_exec, $id_client);           
		}
		catch (QueryLoadComandaException $e) {
			redirectOnError(CT_LOAD_COMANDA_BY_ID);
		}
	}
    $comanda = $comenzi[0];
	$firma = $firme_exec[0];
    $contact_nume = '';
    $contact_id = $comanda->id_contact_exec;
    foreach($firma->contacte as $contact)
        if ($contact->id_contact == $contact_id) {
            $contact_nume = $contact->nume;
            break;
        }        
        
    try {
        $setari = SetariClient::queryLoadSetariClient($db, $id_client);
    }
    catch (QueryLoadSetariException $e) {
        redirectOnError(CT_LOAD_SETARI);
    }
    catch (QuerySettingsNotExistException $e) {
        redirectOnError(CT_SETTINGS_NOT_EXIST);
    }

	header("Pragma: public"); // required                                                                                                                        
    header("Expires: 0");                                                                                                                                    
	header("Content-Description: File Transfer");                                                                                                        
	header("Cache-Control: must-revalidate, post-check=0, pre-check=0");                                                                             
	header("Content-type: application/pdf");                                                                                                                 
	header('Content-Transfer-Encoding: binary');                       
	$cale_fisier = USERS_PATH . $_SESSION['user_logat']->id_user . "/comanda_" . $comanda->id_comanda . ".pdf";                                                                                      
	header("Content-Disposition: attachment; filename=\"" . basename($cale_fisier) . '"');   

	print_comandaWithOO($comanda, $db, $_SESSION['client_logat'], $firma, $contact_nume, $setari);

	readfile($cale_fisier);                                             
	exit();   	
?>
